package com.xiaoyao.novel.velocity;

import java.io.FileOutputStream;
import java.io.StringWriter;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import com.xiaoyao.novel.common.Constant;
import com.xiaoyao.novel.common.Pagin;
import com.xiaoyao.novel.pojo.Book;
import com.xiaoyao.novel.pojo.Category;
import com.xiaoyao.novel.pojo.Chapter;
import com.xiaoyao.novel.pojo.WebInfo;
import com.xiaoyao.novel.service.BookService;
import com.xiaoyao.novel.service.CategoryService;
import com.xiaoyao.novel.service.ChapterService;
import com.xiaoyao.novel.service.WebInfoService;
import com.xiaoyao.novel.util.FileUtil;
import com.xiaoyao.novel.util.SpendClock;

/**
 * 手机页面静态化
 * 
 * @author Administrator
 * 
 */
public class PhoneVelocityStatic {
	static Logger logger = Logger.getLogger(PhoneVelocityStatic.class);
	static VelocityEngine ve = new VelocityEngine();

	public static String webRoot = FileUtil.getWebRoot();
	public static String phoneDir = FileUtil.phoneDir;

	public static String indexDir = "";// "book/";
	public static String bookDir = FileUtil.bookPath;// "book/";
	public static String chapterDir = FileUtil.chapterPath;// "chapter/";
	public static String listDir = FileUtil.listPath;// "chapter/";
	public static String TEMPLATE_DIR = webRoot;

	public static WebInfoService webInfoService = new WebInfoService();
	public static CategoryService categoryService = new CategoryService();
	public static BookService bookService = new BookService();
	public static ChapterService chapterService = new ChapterService();
	public static final int superSize = 9; // 首页超级书籍
	public static final int recommendSize = 20; // 推荐书籍
	static {
		// 初始化
		Properties properties = new Properties();
		// 指定,如"D:/template",但记住只要指定到文件夹就行了
		properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, TEMPLATE_DIR + phoneDir); // 此处的fileDir可以直接用绝对路径来
		properties.setProperty("input.encoding", "UTF-8");
		properties.setProperty("output.encoding", "UTF-8");
		properties.setProperty("file.resource.loader.cache", "true");
		try {
			ve.init(properties);
		} catch (Exception e) {
			logger.error(e);
		}
	}

	/**
	 * 静态化所有手机页面
	 */
	public static void staticPhonePages() {
		staticIndex();
		staticCategory();
		staticBookAndChapters();
	}

	/**
	 * Velocity 静态化页面,
	 * 
	 * @param context
	 *            上下文参数,Map 形式的数据
	 * @param templateFilepath
	 *            模板地址,WebRoot相对 地址
	 * @param outputFilepath
	 *            输出文件地址,绝对地址
	 * @return 静态页面的内容
	 */
	private static String staticPage(VelocityContext context, String templateFilepath, String outputFilepath) {
		String result = "处理错误:请返回";
		try {
			Template template = ve.getTemplate(templateFilepath);
			StringWriter stringWriter = new StringWriter();
			template.merge(context, stringWriter);
			result = stringWriter.toString();
 
			FileOutputStream fos = new FileOutputStream(outputFilepath);
			fos.write(result.getBytes(Constant.CHARSET));
			fos.close();
		  
		} catch (Exception e) {
			logger.error(e);
		}
		return result;
	}

	// ////////////////////////////////////
	// ////////////////////////////////////
	/**
	 * 静态化首页
	 */
	public static void staticIndex() {
		logger.info("静态化手机首页!");
		WebInfo webInfo = webInfoService.getStaticWebInfo();
		List<Category> categoryList = categoryService.getAll();

		Pagin pagin = new Pagin();
		pagin.setPageSize(recommendSize);
		pagin.getSearchParam().put("orderBy", " clickCount desc");
		List<Book> hotList = bookService.search(pagin); // 点击

		pagin = new Pagin();
		pagin.setPageSize(recommendSize);
		pagin.getSearchParam().put("orderBy", " updateTime desc");
		List<Book> newList = bookService.search(pagin); // 最新

		pagin = new Pagin();
		pagin.setPageSize(superSize);
		pagin.getSearchParam().put("orderBy", " isRecommend desc");
		List<Book> superList = bookService.search(pagin);

		VelocityContext context = new VelocityContext();
		context.put("webInfo", webInfo);
		context.put("templateDir", TEMPLATE_DIR);
		context.put("categoryList", categoryList);
		context.put("hotList", hotList);
		context.put("newList", newList);
		context.put("superList", superList);

		String indexTemplateFilepath = "index.vm";
		String indexOutputFilepath = webRoot + phoneDir + indexDir + "index.html";

		staticPage(context, indexTemplateFilepath, indexOutputFilepath);
	}

	/**
	 * 静态化分类
	 */
	public static void staticCategory() {
		WebInfo webInfo = webInfoService.getStaticWebInfo();
		List<Category> categoryList = categoryService.getAll();

		VelocityContext context = new VelocityContext();
		context.put("webInfo", webInfo);
		context.put("templateDir", TEMPLATE_DIR);
		context.put("categoryList", categoryList);

		String indexTemplateFilepath = "list.vm";
		for (Category category : categoryList) {
			logger.info("静态化手机分类:" + category.getCateId());
			List<Book> bookList = categoryService.getCategoryBooks(category.getCateId());
			context.put("category", category);
			context.put("bookList", bookList);
			if (bookList.size() > 0) {
				context.put("book", bookList.get(0));
			}
			String indexOutputFilepath = webRoot + phoneDir + listDir + category.getCateId() + ".html";
			staticPage(context, indexTemplateFilepath, indexOutputFilepath);
		}
	}

	/**
	 * 静态化所有书籍最新 TopN章
	 * 
	 * @param topN
	 */
	public static void staticBookAndChapters(int topN) {
		List<Book> bookList = bookService.getAll();
		for (Book book : bookList) {
			staticBookAndChapters(book, topN);
		}
	}

	/**
	 * 静态化所有书籍最新 章
	 * 
	 * @param topN
	 */
	public static void staticBooks() {
		List<Book> bookList = bookService.getAll();
		for (Book book : bookList) {
			logger.warn("静态化手机书籍:" + book.getBookName() + "," + book.bookId);
			staticBook(book );
		}
	} 

	/**
	 * 静态化书籍. 10秒
	 * 
	 * @param book
	 * @param topN
	 */
	public static void staticBook(Book book ) {
		int bookId = book.bookId;
		book = bookService.getById(bookId);

		WebInfo webInfo = webInfoService.getStaticWebInfo();
		List<Category> categoryList = categoryService.getAll();

		Pagin pagin = new Pagin();
		pagin.setPageSize(superSize);
		pagin.getSearchParam().put("orderBy", " clickCount desc");
		List<Book> hotList = bookService.search(pagin);

		pagin = new Pagin();
		pagin.setPageSize(superSize);
		pagin.setStart(0);
		pagin.getSearchParam().put("orderBy", " isRecommend desc, clickCount desc ");
		List<Book> recommendList = bookService.search(pagin);

		pagin = new Pagin();
		pagin.setPageSize(10000);
		pagin.getSearchParam().put("orderBy", " cid desc ");
		pagin.getSearchParam().put("bookId", bookId + "");
		List<Chapter> chapterList = chapterService.search(pagin); // 顺序
		book.setList(chapterList);

		VelocityContext context = new VelocityContext();
		context.put("webInfo", webInfo);
		context.put("templateDir", TEMPLATE_DIR);
		context.put("book", book);
		context.put("hotList", hotList);
		context.put("categoryList", categoryList);
		context.put("recommendList", recommendList);

		String bookTemplateFilepath = "book.vm";
		String bookOutputFilepath = webRoot + phoneDir + bookDir + bookId + ".html";

		staticPage(context, bookTemplateFilepath, bookOutputFilepath); 
		book.list.clear();
	}
	
	
	
	
	
	/**
	 * 静态化所有书籍最新 章
	 * 
	 * @param topN
	 */
	public static void staticBookAndChapters() {
		List<Book> bookList = bookService.getAllBook();
		for (Book book : bookList) {
			logger.warn("静态化手机书籍:" + book.getBookName() + "," + book.bookId);
			staticBookAndChapters(book, 10000);
		}
	}

	/**
	 * 静态化书籍.最新 topN章节 809章,70秒 335 ,10秒
	 * 
	 * @param book
	 * @param topN
	 */
	public static void staticBookAndChapters(Book book, int topN) {
		int bookId = book.bookId;
		book = bookService.getById(bookId);

		WebInfo webInfo = webInfoService.getStaticWebInfo();
		List<Category> categoryList = categoryService.getAll();

		Pagin pagin = new Pagin();
		pagin.setPageSize(superSize);
		pagin.getSearchParam().put("orderBy", " clickCount desc");
		List<Book> hotList = bookService.search(pagin);

		pagin = new Pagin();
		pagin.setPageSize(superSize);
		pagin.setStart(0);
		pagin.getSearchParam().put("orderBy", " isRecommend desc, clickCount desc ");
		List<Book> recommendList = bookService.search(pagin);

		pagin = new Pagin();
		pagin.setPageSize(10000);
		pagin.getSearchParam().put("orderBy", " cid desc ");
		pagin.getSearchParam().put("bookId", bookId + "");
		List<Chapter> chapterList = chapterService.search(pagin); // 顺序
		book.setList(chapterList);

		VelocityContext context = new VelocityContext();
		context.put("webInfo", webInfo);
		context.put("templateDir", TEMPLATE_DIR);
		context.put("book", book);
		context.put("hotList", hotList);
		context.put("categoryList", categoryList);
		context.put("recommendList", recommendList);

		String bookTemplateFilepath = "book.vm";
		String bookOutputFilepath = webRoot + phoneDir + bookDir + bookId + ".html";

		staticPage(context, bookTemplateFilepath, bookOutputFilepath);
		logger.debug("书籍输出地址:" + bookOutputFilepath);
		int chapterSize = book.list.size(); 
		for (int i = 0; i<=topN && i < chapterSize; i++) { 
			Chapter chapter = book.list.get(i); 
			if (i > 0) { // 有后一张
				chapter.setNextId(book.list.get(i - 1).getCid());
			}
			if (i < chapterSize - 1) { // 有前一张
				chapter.setPrevId(book.list.get(i+ 1).getCid());
			}
			context.put("chapter", chapter);
			String chapterTemplateFilepath = "chapter.vm";
			String chapterOutputFilepath = webRoot + phoneDir + chapterDir + chapter.getCid() + ".html";

			staticPage(context, chapterTemplateFilepath, chapterOutputFilepath);
			logger.info("章节输出地址:" + chapterOutputFilepath);
		}
		book.list.clear();
	}

	public static void staticBookChapters(int bookId){
		Book book = bookService.getById(bookId);
		staticBookAndChapters(book, 1000);
	}

	public static void main(String[] args) {
		SpendClock.start();
//		staticIndex();
//		staticCategory();
//		staticBookAndChapters();
		// staticPhonePages();
		staticBookChapters(248);
		SpendClock.print();
	}

}
